package com.compass.mobile.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentDoctorInfoBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.KEY_DEPARTMENT_ID
import com.compass.mobile.framework.constant.KEY_DOCTOR_ID
import com.compass.mobile.framework.constant.KEY_TYPE
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.ArticleBean
import com.compass.mobile.models.Config
import com.compass.mobile.models.DoctorInfo
import com.compass.mobile.presenters.LectureColumnPresenter
import com.compass.mobile.ui.activity.SpecialColumnActivity
import com.compass.mobile.ui.activity.VideoPlayActivity
import com.compass.mobile.ui.dialog.DoctorGoodAtDialog
import com.compass.mobile.ui.viewModel.DoctorViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import setUrlCircle
import setUrlRound

/**
 * Description： 医生信息fragment
 * Date:2024/5/22 15:34
 */
class DoctorInfoFragment : BaseVBFragment<FragmentDoctorInfoBinding>() {
    private val doctorViewModel: DoctorViewModel by activityViewModels()
    private var doctorId: String? = null
    private var doctorInfo: DoctorInfo? = null
    private var departmentId: String? = null
    private var comeType: String? = null
    private var articles: MutableList<ArticleBean> = mutableListOf()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    override fun initView(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            comeType = it.getString(KEY_TYPE)
            doctorId = it.getString(KEY_DOCTOR_ID)
            departmentId = it.getString(KEY_DEPARTMENT_ID)
        }
        initSpecialColumn()

    }

    private var mPage = 1
    override fun initData() {
        //获取数据

        doctorViewModel.doctorHomePageLiveData.observe(this) {
            it?.let {
                initDoctorInfo(it.doctor, it.config)
            }
        }

        doctorViewModel.articleLiveData.observe(this) {
            it?.let { list ->
                articles = list
                if (articles.isNotEmpty()) {
                    mBinding?.emptyView?.gone()
                    mBinding?.tvMore?.visible()
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, articles)
                } else {
                    mBinding?.tvMore?.gone()
                    mBinding?.emptyView?.visible()
                }
            } ?: kotlin.run {
                mBinding?.tvMore?.gone()
                mBinding?.emptyView?.visible()
            }
        }
    }


    /**
     * 设置医生信息
     */
    private fun initDoctorInfo(doctorHomePage: DoctorInfo, config: Config) {
        doctorInfo=doctorHomePage
        mBinding?.imgHead?.setUrlCircle(doctorHomePage.avatar)
        mBinding?.tvDoctorName?.text = doctorHomePage.name
        mBinding?.tvPositionName?.text = doctorHomePage.positionName
        mBinding?.tvDepartments?.text = doctorHomePage.departmentName
        mBinding?.tvHospitalLevel?.text = doctorHomePage.hospitalLevel
        mBinding?.tvConsultationNum?.text =  "问诊数量：${doctorHomePage.statistics.consultationNum}"
        mBinding?.tvSubmit?.text = "${doctorHomePage.statistics.favorableRate}"
        //处方权
        if (doctorHomePage.prescriptionAllow == "1") mBinding?.tvPrescription?.visible() else mBinding?.tvPrescription?.gone()

        mBinding?.tvPracticeScope?.text = "执业范围: ${getPracticeScope(doctorHomePage.practiceScope)}"
        mBinding?.tvCertifiedCode?.text = "资格证书编号: ${getCertifiedCode(doctorHomePage.certifiedCode)}"
        mBinding?.tvMeritIllness?.text = doctorHomePage.meritIllness
        mBinding?.tvIntroduce?.text = doctorHomePage.introduce


        //焦点请求
        mBinding?.llIndependentBilling?.requestFocus()

    }


    private fun getPracticeScope(practiceScope:String?): String {
        if (practiceScope.isNullOrEmpty()) {
            return "暂未设置"
        }
        return practiceScope
    }

   private fun getCertifiedCode(certifiedCode:String?): String {
        if (certifiedCode.isNullOrEmpty()) {
            return "暂未设置"
        }
        return certifiedCode
    }

    override fun intListener() {
        mBinding?.llMore?.onClick {
            SpecialColumnActivity.start(requireContext(), doctorId)

        }
        mBinding?.llIndependentBilling?.onClick {

            DoctorGoodAtDialog.Builder(requireActivity(),doctorInfo).show()
        }
    }



    /**
     * 初始化专栏
     */
    private fun initSpecialColumn() {
        mBinding?.clyColumn?.visible()
        mBinding?.caseItem?.post {
            // 使用获取到的宽度
            val width = mBinding?.caseItem?.width
            width?.let {
                specialColumn(it)
            }
        }
    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val  item =articles[position]
            VideoPlayActivity.start(requireContext(),item.videoUrl)
        }
    }


    @SuppressLint("RestrictedApi")
    fun specialColumn(width: Int) {
        mBinding?.caseItem?.setNumColumns(2)
        mBinding?.caseItem?.horizontalSpacing = dpToPx(10)
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)
        val finalWidth = width - dpToPx(80)
        val lectureColumnPresenter =
            LectureColumnPresenter()
        lectureColumnPresenter.setFinalWidth(finalWidth / 2)
        arrayObjectAdapter = ArrayObjectAdapter(lectureColumnPresenter)
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )
        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        mBinding?.caseItem?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, articles)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_SMALL, false
        )

        doctorViewModel.getArticleList(doctorId, "2", mPage, 4)
    }


}